<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "user_store_log".
 *
 * @property int $id
 * @property int $user_id
 * @property int $num 剩下
 * @property int $change 加减
 * @property int $result 现在多少
 * @property int $order_id 订单ID, 返佣和消费
 * @property string $text 备注(充值, 返佣[重算], 消费, 提现[驳回])
 * @property string $create_time
 * @property string $update_time
 * @property int $type 1 下单, 2 出货 3 提货
 */
class UserStoreLog extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_store_log';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'num', 'change', 'result', 'order_id'], 'integer'],
            [['create_time', 'update_time'], 'safe'],
            [['text'], 'string', 'max' => 255],

            [['type'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'num' => 'Num',
            'change' => 'Change',
            'result' => 'Result',
            'order_id' => 'Order ID',
            'text' => 'Text',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public static function addLog($user_id, $num, $change, $result, $text = '', $type = 1, $order_id = 0)
    {
        $model = new self();
        $model->user_id = $user_id;
        $model->num = $num;
        $model->change = $change;
        $model->result = $result;
        $model->text = $text;
        $model->type = $type;
        $model->order_id = $order_id;

        if ($model->save()) {
            return $model;
        }

    }
}
